// src/routes/roles.ts
import express, { Request, Response } from "express";
import Role from "../models/Role";

const router = express.Router();

// 获取角色列表
router.get("/", async (req: Request, res: Response) => {
  try {
    const roles = await Role.findAll();
    res.json(roles);
  } catch (error) {
    res.status(500).json({ message: "Error retrieving roles", error });
  }
});

// 创建新角色
router.post("/", async (req: Request, res: Response) => {
  const { role_name, role_desc } = req.body;
  try {
    const newRole = await Role.create({ role_name, role_desc });
    res.status(201).json(newRole);
  } catch (error) {
    res.status(500).json({ message: "Error creating role", error });
  }
});

// 获取指定角色信息
router.get("/:id", async (req: Request, res: Response) => {
  const { id } = req.params;
  try {
    const role = await Role.findByPk(id);
    if (!role) {
      res.status(404).json({ message: "Role not found" });
    } else {
      res.json(role);
    }
  } catch (error) {
    res.status(500).json({ message: "Error retrieving role", error });
  }
});

// 更新角色信息
router.put("/:id", async (req: Request, res: Response) => {
  const { id } = req.params;
  const { role_name, role_desc } = req.body;
  try {
    const role = await Role.findByPk(id);
    if (!role) {
      res.status(404).json({ message: "Role not found" });
    } else {
      role.role_name = role_name || role.role_name;
      role.role_desc = role_desc || role.role_desc;
      await role.save();
      res.json(role);
    }
  } catch (error) {
    res.status(500).json({ message: "Error updating role", error });
  }
});

// 删除角色
router.delete("/:id", async (req: Request, res: Response) => {
  const { id } = req.params;
  try {
    const role = await Role.findByPk(id);
    if (!role) {
      res.status(404).json({ message: "Role not found" });
    } else {
      await role.destroy();
      res.status(204).send();
    }
  } catch (error) {
    res.status(500).json({ message: "Error deleting role", error });
  }
});

export default router;
